package com.xuelang.pipeline.worker.entry.pod;

import com.xuelang.pipeline.worker.app.pod.PodService;
import com.xuelang.pipeline.worker.client.common.result.ApiResult;
import com.xuelang.pipeline.worker.client.pod.IPodService;
import com.xuelang.pipeline.worker.client.pod.dto.PodQueryDTO;
import com.xuelang.pipeline.worker.client.pod.dto.QueryDTO;
import io.kubernetes.client.openapi.models.V1PodList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import jakarta.validation.Valid;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author liuyuan.ly
 * @since 2024/5/29 10:33
 */
@Slf4j
@RestController
@RequestMapping("/pipeline/worker/")
public class PodController implements IPodService {

    @Autowired
    private PodService podService;

    @Override
    public ApiResult<V1PodList> getPodList(QueryDTO queryDTO) {
        return ApiResult.success(podService.getPodList(queryDTO));
    }

    @Override
    public ApiResult<String> getPodLog(PodQueryDTO queryDTO) {

        return ApiResult.success(podService.getPodLog(queryDTO));
    }

    @Override
    public ResponseEntity<StreamingResponseBody> streamPodLog(@Valid PodQueryDTO queryDTO) {
        InputStream logStream = podService.streamPodLog(queryDTO);

        // 使用更大的缓冲区（如 8KB）
        final int BUFFER_SIZE = 8192;

        StreamingResponseBody responseBody = outputStream -> {
            try (InputStream autoCloseStream = logStream) { // 确保流自动关闭
                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead;
                while ((bytesRead = autoCloseStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush(); // 确保最后一次写入冲刷
            } catch (IOException e) {
                // 记录错误日志（替换为实际日志框架）
                log.error("Error streaming pod log", e);
                throw e; // 重新抛出以触发 Spring 的错误处理
            }
        };

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=pod_log.log")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(responseBody);
    }
}
